package com.dingreading.cloud.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.dingreading.cloud.admin.entity.CorporationContract;
import com.dingreading.cloud.admin.entity.CorporationContractFile;
import com.dingreading.cloud.admin.service.CorporationContractFileService;
import com.dingreading.cloud.admin.service.CorporationContractService;
import com.dingreading.cloud.admin.util.ContractFileUtil;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RefreshScope
@RestController
@RequestMapping("/system/corporationContract")
@Api(tags = "总部-加盟商合同管理")
public class CorporationContractController {

    @Resource
    private CorporationContractService corporationContractService;
    @Resource
    private CorporationContractFileService corporationContractFileService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList")
    public R<Object> pageList(
            HttpServletRequest request,
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "加盟商uid") @RequestParam(value = "corpUid", required = false) String corpUid,
            @ApiParam(value = "合同编号") @RequestParam(value = "keyword", required = false) String keyword
    ) {
        Page<CorporationContract> page = corporationContractService.pageList(pageUtil, corpUid, keyword);

        List<CorporationContract> list = page.getRecords();
        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> contractIds = list.stream().map(CorporationContract::getId).collect(Collectors.toList());

            List<CorporationContractFile> fileList = corporationContractFileService.listByContractIdIn(contractIds);
            if (CollectionUtils.isNotEmpty(fileList)) {
                Map<Long, List<CorporationContractFile>> map = fileList.stream()
                        .collect(Collectors.groupingBy(CorporationContractFile::getContractId, Collectors.toList()));
                // 合同文件添加token
                String ipAddr = IpUtil.getIpAddr(request);
                String token = ContractFileUtil.getToken(ipAddr);
                for (CorporationContract contract : list) {
                    List<CorporationContractFile> contractFiles = map.get(contract.getId());
                    if (CollectionUtils.isNotEmpty(contractFiles)) {
                        contractFiles.forEach(file -> {
                            file.setUrl(file.getUrl() + token);
                        });
                        contract.setFileList(contractFiles);
                    }
                }
            }
        }

        PageBeanDto data = new PageBeanDto();
        data.setTotal(page.getTotalRow());
        data.setList(page.getRecords());
        return R.ok(data);
    }

    @ApiOperation(value = "按加盟商uid获取合同列表")
    @PostMapping(value = "/getList")
    public R<Object> getList(
            HttpServletRequest request,
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "加盟商uid") @RequestParam(value = "corpUid", required = false) String corpUid
    ) {
        List<CorporationContract> list = corporationContractService.listByCorpUid(corpUid);

        if (CollectionUtils.isNotEmpty(list)) {
            List<Long> contractIds = list.stream().map(CorporationContract::getId).collect(Collectors.toList());

            List<CorporationContractFile> fileList = corporationContractFileService.listByContractIdIn(contractIds);
            if (CollectionUtils.isNotEmpty(fileList)) {
                Map<Long, List<CorporationContractFile>> map = fileList.stream()
                        .collect(Collectors.groupingBy(CorporationContractFile::getContractId, Collectors.toList()));
                // 合同文件添加token
                String ipAddr = IpUtil.getIpAddr(request);
                String token = ContractFileUtil.getToken(ipAddr);
                for (CorporationContract contract : list) {
                    List<CorporationContractFile> contractFiles = map.get(contract.getId());
                    if (CollectionUtils.isNotEmpty(contractFiles)) {
                        contractFiles.forEach(file -> {
                            file.setUrl(file.getUrl() + token);
                        });
                        contract.setFileList(contractFiles);
                    }
                }
            }
        }
        return R.ok(list);
    }

    @ApiOperation(value = "根据公司uid获取信息")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            HttpServletRequest request,
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "合同id") @RequestParam(value = "id") Long id
    ) {
        CorporationContract data = corporationContractService.getById(id);
        if (null == data)
            return R.fail("未查询到合同");

        List<CorporationContractFile> fileList = corporationContractFileService.listByContractId(id);
        if (CollectionUtils.isNotEmpty(fileList)) {
            // 合同文件添加token
            String ipAddr = IpUtil.getIpAddr(request);
            String token = ContractFileUtil.getToken(ipAddr);
            fileList.forEach(file -> {
                file.setUrl(file.getUrl() + token);
            });
            data.setFileList(fileList);
        }

        return R.ok(data);
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "创建/更新合同信息")
    @PostMapping(value = "/newBean", produces = "application/json; charset=UTF-8")
    public R<Object> newBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "加盟商uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "合同编号") @RequestParam(value = "contractCode") String contractCode,
            @ApiParam(value = "合同描述") @RequestParam(value = "content") String content,
            @ApiParam(value = "合同开始日期") @RequestParam(value = "beginDate") String beginDate,
            @ApiParam(value = "合同结束日期") @RequestParam(value = "endDate") String endDate,
            @ApiParam(value = "签约日期") @RequestParam(value = "signDate") String signDate,
            @ApiParam(value = "是否签署 1.是 0.否") @RequestParam(value = "signStatus") Integer signStatus,
            @ApiParam(value = "文件地址集合[{id:0,url:''}]") @RequestParam(value = "fileJson", required = false) String fileJson
    ) throws Exception {
        if (StringUtils.isBlank(contractCode))
            return R.fail("未填写合同编号");
        if (signStatus == null)
            return R.fail("未选择签署状态");

        CorporationContract data = null;
        if (null == id || id <= 0) {
            data = new CorporationContract();
            data.setAddStaffUid(headStaffUid);
            data.setAddStaffName(headStaffName);
            data.setCorpUid(corpUid);
        } else {
            data = corporationContractService.getById(id);
            if (null == data)
                return R.fail("未查询到合同");
        }
        data.setContractCode(contractCode);
        data.setContent(content);
        data.setBeginDate(DateUtil.parseDate(beginDate));
        data.setEndDate(DateUtil.parseDate(endDate));
        data.setSignDate(DateUtil.parseDate(signDate));
        data.setSignStatus(signStatus);
        data.setLastStaffUid(headStaffUid);
        data.setLastStaffName(headStaffName);
        corporationContractService.saveOrUpdate(data);

        // 保存合同文件
        if (StringUtils.isNotBlank(fileJson)) {
            List<CorporationContractFile> fileList = JSONArray.parseArray(fileJson, CorporationContractFile.class);

            List<Long> ids = new ArrayList<>();
            for (CorporationContractFile file : fileList) {
                if (file.getId() == null || file.getId() <= 0) {
                    file.setContractId(data.getId());
                    file.setCorpUid(corpUid);
                    file.setAddStaffUid(headStaffUid);
                    file.setAddStaffName(headStaffName);
                } else {
                    ids.add(file.getId());
                }
            }

            // 先删除不保存的文件
            corporationContractFileService.deleteByFileIdsNotIn(data.getId(), ids);

            corporationContractFileService.saveOrUpdateBatch(fileList);
        } else {
            corporationContractFileService.deleteByContractId(data.getId());
        }

        return R.ok();
    }

    @ApiOperation(value = "更新签署状态")
    @PostMapping(value = "/updateSignStatus", produces = "application/json; charset=UTF-8")
    public R<Object> updateSignStatus(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "合同id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "是否签署 1.是 0.否") @RequestParam(value = "signStatus") Integer signStatus
    ) {
        CorporationContract data = corporationContractService.getById(id);
        if (data == null)
            return R.fail("未查询到合同");
        if (data.getSignStatus().equals(1)) {
            if (TimeUtil.moreThanDay(data.getSignDate(), 30)) {
                return R.fail("签署超过30天，不能操作");
            }
        }

        corporationContractService.updateSignStatus(id, signStatus);
        return R.ok();
    }

    @ApiOperation(value = "删除合同")
    @PostMapping(value = "/deleteBean", produces = "application/json; charset=UTF-8")
    public R<Object> deleteBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "合同id") @RequestParam(value = "id") Long id
    ) {
        CorporationContract data = corporationContractService.getById(id);
        if (data == null)
            return R.fail("未查询到合同");

        boolean b = corporationContractService.removeById(id);
        if (!b)
            return R.failDel();

        int i = corporationContractFileService.deleteByContractId(id);
        return R.ok();
    }

    @ApiOperation(value = "上传文件")
    @PostMapping(value = "/uploadFile", produces = "application/json; charset=UTF-8")
    public R<Object> uploadFile(
            HttpServletRequest request,
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "文件") @RequestPart(value = "file") MultipartFile file
    ) throws Exception {
        // 上传图片到服务器
        R<String> r = LocalFileUtil.uploadFile(LocalFileUtil.contractBaseDir, file);
        if (R.isError(r))
            return R.fail(r.getMsg());
        // 合同文件添加token
        String ipAddr = IpUtil.getIpAddr(request);
        String token = ContractFileUtil.getToken(ipAddr);
        return R.ok(r.getData() + token);
    }

//    @ApiOperation(value = "获取合同的上传文件")
//    @PostMapping(value = "/getContractFiles", produces = "application/json; charset=UTF-8")
//    public R<Object> getContractFiles(
//            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
//            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
//            @ApiParam(value = "合同id") @RequestParam(value = "contractId") Long contractId
//    ) {
//        
//
//        List<CorporationContractFile> list = corporationContractFileService.listByContractId(contractId);
//
//        return R.ok(list);
//    }

//    @ApiOperation(value = "上传合同文件")
//    @PostMapping(value = "/uploadFile", produces = "application/json; charset=UTF-8")
//    public R<Object> uploadFile(
//            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
//            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
//            @ApiParam(value = "合同id") @RequestParam(value = "contractId") Long contractId,
//            @ApiParam(value = "文件地址") @RequestParam(value = "url") String url
//    ) {
//        
//
//        CorporationContract data = corporationContractService.getById(contractId);
//        if (data == null)
//            return R.fail("未查询到合同");
//
//        CorporationContractFile file = new CorporationContractFile();
//        file.setAddStaffUid(headStaffUid);
//        file.setAddStaffName(headStaffName);
//        file.setCorpUid(data.getCorpUid());
//        file.setContractId(contractId);
//        file.setUrl(url);
//        corporationContractFileService.saveOrUpdate(file);
//
//        return R.ok();
//    }
//
//    @ApiOperation(value = "删除合同文件")
//    @PostMapping(value = "/deleteFile", produces = "application/json; charset=UTF-8")
//    public R<Object> deleteFile(
//            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
//            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
//            @ApiParam(value = "文件id") @RequestParam(value = "id") Long id
//    ) {
//        
//
//        CorporationContractFile data = corporationContractFileService.getById(id);
//        if (data == null)
//            return R.fail("未查询到文件");
//
//        int i = corporationContractFileService.deleteFile(id);
//        if (i <= 0)
//            return result.deleteError();
//
//        // 删除阿里云文件
//        deleteOssFiles(data.getUrl());
//        return R.ok();
//    }

    /**
     * 删除阿里云文件
     */
//    private void deleteOssFiles(String url) {
//        // 生产环境且阿里云文件地址不为空，才能删除
//        if (AccountUtil.judgeProd(envi) && StringUtils.isNotBlank(url)) {
//            // 删除阿里云图片
//            OSSClientUtil ossClientUtil = new OSSClientUtil();
//            ossClientUtil.initOss();
//            ossClientUtil.deleteFile(OSSClientUtil.publicBucket, url);
//        }
//    }

}